// pages/room5/storyCommitPage/storyCommitPage.js
import room4TestData from "../../testData/testR4Data";
const app = getApp();
var mfApi = require('../../../api/api.js');
// let drawQrcode = require("../../../utils/weapp.qrcode");
import TWEEN from './../../normalRoom/tween.js';

let ZW_Ctx0 = null;
let ZW_Canvas0 = null;
var Pixel_Ratio0 = 2;
var ZW_DrawArray = [];

Page({

        /**
         * 页面的初始数据
         */
        data: {
                baseUrl: app.globalData.baseUrl,

                /**
                 * 房间资源
                 */
                roomResourceData: room4TestData,

                userIcon: app.globalData.userIcon ? app.globalData.userIcon : '',
                userName: app.globalData.userName ? app.globalData.userName : '',

                // 选择的图片
                selectImageFile: null,
                shotImageUrl:null,
                // 输入的内容
                inputTitleStr: null,
                inputDescStr: null,

                // 提交成功
                commitStoryId: null,
                // 内容审核不通过
                isShowCommitError: false,

                // 是不是第二步确认提交
                isConfirmMode: false,

                isCommitComplete: false,
                showCommitResultView: false,
                showVideoAniView: false,

                lastX:0,
                lastY:0,

                // 返回键
                top: 0,
                h: 0 //胶囊高度
        },

        onShareTimeline:function(){
 
        },
        /**
         * 生命周期函数--监听页面加载
         */
        onLoad: function (options) {
                this.setData({
                        userIcon: app.globalData.userIcon ? app.globalData.userIcon : '',
                        userName: app.globalData.userName ? app.globalData.userName : '',
                        top: app.menu.top,
                        h: app.menu.height
                })
        }, 
        drawFrame() {
                //console.log('draw');
                if(!ZW_Ctx0) return;
                ZW_Ctx0.clearRect(0,0,ZW_Canvas0.width,ZW_Canvas0.height);
          
          
                if(ZW_DrawArray.length < 1) return;
          
                if(!ZW_DrawArray[0] || !ZW_DrawArray[0].obj || !ZW_DrawArray[4] || !ZW_DrawArray[4].obj) return;
          
                if(ZW_DrawArray[0] && ZW_DrawArray[0].visible)
                  {
                    ZW_Ctx0.drawImage(
                      ZW_DrawArray[0].obj,
                      ZW_DrawArray[0].left,
                      ZW_DrawArray[0].top,
                      ZW_DrawArray[0].width,
                      ZW_DrawArray[0].height
                    );
                  }
          
                ZW_Ctx0.globalCompositeOperation = 'source-over';
                if(ZW_DrawArray[1] && ZW_DrawArray[1].visible)
                  {
                    //ZW_DrawArray[1].left += 1;
                    ZW_Ctx0.drawImage(
                      ZW_DrawArray[1].obj,
                      ZW_DrawArray[1].left,
                      ZW_DrawArray[1].top,
                      ZW_DrawArray[1].width,
                      ZW_DrawArray[1].height
                    );
                  }
          
                ZW_Ctx0.globalCompositeOperation = 'xor';
                
                if(ZW_DrawArray[2] && ZW_DrawArray[2].visible)
                  {
                    ZW_Ctx0.drawImage(
                      ZW_DrawArray[2].obj,
                      ZW_DrawArray[2].left,
                      ZW_DrawArray[2].top,
                      ZW_DrawArray[2].width,
                      ZW_DrawArray[2].height
                    );
                  }
          
                  ZW_Ctx0.globalCompositeOperation = 'destination-atop';
                
                if(ZW_DrawArray[3] && ZW_DrawArray[3].visible)
                  {
                    ZW_Ctx0.drawImage(
                      ZW_DrawArray[3].obj,
                      ZW_DrawArray[3].left,
                      ZW_DrawArray[3].top,
                      ZW_DrawArray[3].width,
                      ZW_DrawArray[3].height
                    );
                  }
          
                  ZW_Ctx0.globalCompositeOperation = 'source-over';
                
                if(ZW_DrawArray[4] && ZW_DrawArray[4].visible)
                  {
                    ZW_Ctx0.drawImage(
                      ZW_DrawArray[4].obj,
                      ZW_DrawArray[4].left,
                      ZW_DrawArray[4].top,
                      ZW_DrawArray[4].width,
                      ZW_DrawArray[4].height
                    );
                  }
              },
        initCanvas() {
                for (var i = 0; i < 5; i++) {
                        ZW_DrawArray.push({
                                obj: null,
                                left: 0,
                                top: 0,
                                width: 360 * Pixel_Ratio0,
                                height: 387 * Pixel_Ratio0,
                                visible: false
                        });
                }
                wx.getImageInfo({
                        src: 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/cream/images/select-frame%20.png',
                        success(res) {
                                console.log(res.path);
                                let tempImage = ZW_Canvas0.createImage();
                                tempImage.src = res.path;
                                tempImage.onload = () => {
                                        ZW_DrawArray[0] = {
                                                obj: tempImage,
                                                left: 0,
                                                top: 0,
                                                width: 360 * Pixel_Ratio0,
                                                height: 387 * Pixel_Ratio0,
                                                visible: true
                                        };
                                }
                        }
                })

                wx.getImageInfo({
                        src: 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/cream/images/white.png',
                        success(res) {
                                console.log(res.path);
                                let tempImage = ZW_Canvas0.createImage();
                                tempImage.src = res.path;
                                tempImage.onload = () => {
                                        ZW_DrawArray[1] = {
                                                obj: tempImage,
                                                left: 0,
                                                top: 0,
                                                width: 360 * Pixel_Ratio0,
                                                height: 387 * Pixel_Ratio0,
                                                visible: false
                                        };
                                }
                        }
                })
                wx.getImageInfo({
                        src: 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/cream/images/mask1.png',
                        success(res) {
                                console.log(res.path);
                                let tempImage = ZW_Canvas0.createImage();
                                tempImage.src = res.path;
                                tempImage.onload = () => {
                                        ZW_DrawArray[2] = {
                                                obj: tempImage,
                                                left: 0,
                                                top: 0,
                                                width: 360 * Pixel_Ratio0,
                                                height: 387 * Pixel_Ratio0,
                                                visible: true
                                        };
                                }
                        }
                })
                wx.getImageInfo({
                        src: 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/cream/images/mask2.png',
                        success(res) {
                                console.log(res.path);
                                let tempImage = ZW_Canvas0.createImage();
                                tempImage.src = res.path;
                                tempImage.onload = () => {
                                        ZW_DrawArray[3] = {
                                                obj: tempImage,
                                                left: 0,
                                                top: 0,
                                                width: 360 * Pixel_Ratio0,
                                                height: 387 * Pixel_Ratio0,
                                                visible: true
                                        };
                                }
                        }
                })
                wx.getImageInfo({
                        src: 'https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/cream/images/door.png',
                        success(res) {
                                console.log(res.path);
                                let tempImage = ZW_Canvas0.createImage();
                                tempImage.src = res.path;
                                tempImage.onload = () => {
                                        ZW_DrawArray[4] = {
                                                obj: tempImage,
                                                left: 0,
                                                top: 0,
                                                width: 360 * Pixel_Ratio0,
                                                height: 387 * Pixel_Ratio0,
                                                visible: true
                                        };
                                }
                        }
                })
                return;
        },
        async shotCanvasImage() {
                let _self = this;
                return new Promise((resolve, reject) => {

                        setTimeout(() => {
                                wx.canvasToTempFilePath({
                                        canvas: ZW_Canvas0,
                                        success: (res) => {
                                                console.log("shotQrCode === ", res)
                                                _self.setData({
                                                        shotImageUrl: res.tempFilePath
                                                })
                                                resolve({
                                                        code: 0,
                                                })
                                        },
                                        fail: err => {
                                                console.log("shotQrCode === err ", err)
                                        }
                                })
                        }, 20);


                })
        },
        onReady() {
                const query = wx.createSelectorQuery()
                ZW_DrawArray = [];
                query.select('#indexcanvas')
                        .fields({
                                node: true,
                                size: true
                        })
                        .exec((res) => {
                                ZW_Canvas0 = res[0].node
                                ZW_Ctx0 = ZW_Canvas0.getContext('2d')

                                const dpr = wx.getSystemInfoSync().pixelRatio
                                ZW_Canvas0.width = 360 * Pixel_Ratio0;
                                ZW_Canvas0.height = 387 * Pixel_Ratio0;
                                //ZW_Ctx0.scale(dpr, dpr)
                                this.initCanvas();

                                setInterval(() => {
                                        this.drawFrame();
                                      }, 30);
                        })
        },
        touchStart(event) {
                this.setData({
                        lastX: event.touches[0].x,
                        lastY: event.touches[0].y
                })
                console.log(event);
                // this.lastX = event.touches[0].x;
                // this.lastY = event.touches[0].y;
        },
        touchMove(event) {
                console.log(event);
                var offsetX = event.touches[0].x-this.data.lastX;
                var offsetY = event.touches[0].y-this.data.lastY;

                ZW_DrawArray[1].left += offsetX*2;
                ZW_DrawArray[1].top += offsetY*2;

                this.setData({
                        lastX: event.touches[0].x,
                        lastY: event.touches[0].y
                })

                // this.lastX = event.touches[0].clientX;
                // this.lastY = event.touches[0].clientY;

        },
        touchEnd(event) {
                
        },
        onScaleClick1(){
                ZW_DrawArray[1].left -= 0.05 * ((360 * Pixel_Ratio0 / 2) - ZW_DrawArray[1].left)
                ZW_DrawArray[1].top -= 0.05 * ((387 * Pixel_Ratio0 / 2) - ZW_DrawArray[1].top)

                ZW_DrawArray[1].width *= 1.05;
                ZW_DrawArray[1].height *= 1.05;
        },
        onScaleClick2(){
                ZW_DrawArray[1].left += 0.05 * ((360 * Pixel_Ratio0 / 2) - ZW_DrawArray[1].left)
                ZW_DrawArray[1].top += 0.05 * ((387 * Pixel_Ratio0 / 2) - ZW_DrawArray[1].top)

                ZW_DrawArray[1].width *= 0.95;
                ZW_DrawArray[1].height *= 0.95;
        },
        onReuploadClick(){
                this.setData({
                        selectImageFile: null
                })
                ZW_DrawArray[0].visible = true;
                ZW_DrawArray[1] = null;
                console.log('reupload');
        },
        onAddImageClick() {
                let _self = this;
                wx.chooseImage({
                        count: 1,
                        sizeType: ['compressed'],
                        sourceType: ['album', 'camera'],
                        success(res) {
                                // tempFilePath可以作为img标签的src属性显示图片
                                const tempFilePaths = res.tempFilePaths;
                                // if (tempFilePaths[0].size > 1500000) {
                                //         wx.showToast({
                                //                 title: '图片不要超过1.5M',
                                //                 icon: "none"
                                //         })
                                //         return;
                                // }

                                console.log('pic 1');
                                
                                let tempImage = ZW_Canvas0.createImage();
                                tempImage.src = res.tempFilePaths[0];
                                tempImage.onload = () => {
                                        var w = tempImage.width;
                                        var h = tempImage.height;

                                        console.log('pic 2');
                                        ZW_DrawArray[0].visible = false;
                                        _self.setData({
                                                selectImageFile: res.tempFilePaths[0]
                                        })
                                        if (w > h) {

                                            ZW_DrawArray[1] = {
                                                obj: tempImage,
                                                left: (360 * Pixel_Ratio0 - 387 * Pixel_Ratio0 * (w / h)) / 2,
                                                top: 0,
                                                width: 387 * Pixel_Ratio0 * (w / h),
                                                height: 387 * Pixel_Ratio0,
                                                visible: true,
                                            };
                                        } else {
                                            ZW_DrawArray[1] = {
                                                obj: tempImage,
                                                left: 0,
                                                top: (387 * Pixel_Ratio0 - (h / w) * 360 * Pixel_Ratio0) / 2,
                                                width: 360 * Pixel_Ratio0,
                                                height: (h / w) * 360 * Pixel_Ratio0,
                                                visible: true,
                                            };
                                        }
                                        // ZW_DrawArray[1] = {obj:tempImage,left:0,top:(387*Pixel_Ratio0-(h/w)*360*Pixel_Ratio0)/2,width:360*Pixel_Ratio0,height:(h/w)*360*Pixel_Ratio0,visible:true};

                                        // ZW_DrawArray.push({obj:tempImage,left:0,top:0,width:360*Pixel_Ratio0,height:387*Pixel_Ratio0,visible:true});
                                }
                                //console.log(res.tempFilePaths[0]);
                        }
                })
        },

        /**
         * 标题输入
         * @param {*} e 
         */
        bindTitleInput(e) {
                this.setData({
                        inputTitleStr: e.detail.value
                })
        },
        
        /**
         * 内容输入
         * @param {*} e 
         */
        bindDescInput(e) {
                this.setData({
                        inputDescStr: e.detail.value
                })
        },

        /**
         * 输入模式input切换到确认confirm
         */
        async onPreCommitClick() {
               

                if (!this.data.selectImageFile || !this.data.inputDescStr
                        || !this.data.inputTitleStr) {
                        return;
                }
                // await this.onCommitClick();
                this.setData({
                        isConfirmMode: true
                })
        },

        async onCommitClick() {
                
                if (!this.data.selectImageFile || !this.data.inputDescStr
                        || !this.data.inputTitleStr) {
                        return;
                }

                wx.showLoading({
                        mask: true,
                        title: "加载中",
                });
                ZW_DrawArray[0].visible = false;
                ZW_DrawArray[2].visible = false;
                ZW_DrawArray[3].visible = false;
                ZW_DrawArray[4].visible = false;

                this.drawFrame();

                let re = await this.shotCanvasImage();

                // wx.saveImageToPhotosAlbum({
                //         filePath: this.data.shotImageUrl,
                //         success: data => {
                //                 wx.showToast({
                //                         title: '保存成功',
                //                 })
                //                 wx.hideLoading();
                //         },
                //         fail: err => {
                //                 wx.showToast({
                //                         title: '保存失败',
                //                 })
                //                 wx.hideLoading();
                //         }
                // })

                ZW_DrawArray[1].visible = true;
                ZW_DrawArray[2].visible = true;
                ZW_DrawArray[3].visible = true;
                ZW_DrawArray[4].visible = true;
            
                if (re.code != 0) {
                        wx.showToast({
                                icon: "none",
                                title: '图片生成失败',
                        })
                        wx.hideLoading();
                        return;
                }

                // wx.showToast({
                //         icon: "none",
                //         title: this.data.shotImageUrl,
                // })
                // 上传
                let upres = await mfApi.uploadFile(
                        "user-story",
                        this.data.shotImageUrl
                );

                console.log('upres')
                if (upres.code != 200) {
                        wx.hideLoading();
                        wx.showToast({
                                icon: "none",
                                title: '后端服务异常',
                        })
                        return;
                }else
                {
                        wx.hideLoading();
                        // wx.showToast({
                        //         icon: "none",
                        //         title: '成功上传',
                        // })  
                }

                // 提交
                let commitres = await mfApi.http(mfApi.saveRoom5Story(app.globalData.openId), "POST", {
                        // let commitres = await mfApi.http(mfApi.saveRoom5Story("111"), "POST", {
                        "storyDes": this.data.inputDescStr,
                        "storyImgUrl": upres.result.filePath,
                        "storyTitle": this.data.inputTitleStr,
                        "avatar": this.data.userIcon,
                        "nickName": this.data.userName,
                })

                app.saveTrack(`R5-发表故事`);
                
                if (commitres.code == 10001) {
                        wx.hideLoading();
                        this.setData({
                                isShowCommitError: true
                        })
                        return;
                } else if (commitres.code != 200) {
                        wx.hideLoading();
                        wx.showToast({
                                icon: "none",
                                title: commitres.message,
                        })
                        return;
                }

                // 回查story信息
                let infores = await mfApi.http(mfApi.getStoryById(commitres.result.storyId), "POST");
                wx.hideLoading();
                
                if(app.globalData.needFirstStoryTip) {
                        app.globalData.needFirstStoryTip = false;
                        this.setData({
                                commitStoryId: commitres.result.storyId,
                                isCommitComplete: true,
                                showCommitResultView: true,
                                shotImageUrl: infores.result.storyImgUrl,
                        })
        
                        setTimeout(() => {
                                this.setData({
                                        isCommitComplete: true,
                                        showCommitResultView: false,
                                        showVideoAniView: true
                                })
                        }, 3000);
                } else {
                        this.setData({
                                commitStoryId: commitres.result.storyId,
                                shotImageUrl: infores.result.storyImgUrl,

                                isCommitComplete: true,
                                showCommitResultView: false,
                                showVideoAniView: true
                        })

                        wx.showToast({
                          title: '故事提交成功',
                        })
                }


        },

        onVideoAniFinish() {
                wx.redirectTo({
                        url: `/pages/room5/storyResultPage/storyResultPage?storyId=${this.data.commitStoryId}`,
                })
        },

        goBack() {
                wx.navigateBack();
        },

        onTipBtnClick() {
                this.setData({
                        isShowCommitError: false,
                        isConfirmMode: false,
                        // inputTitleStr: null,
                        // inputDescStr: null,
                })
        },

        onShareAppMessage(object) {
                return {
                        title: 'LA MER邀你一同参展，探寻属于你的自愈空间',
                        path: `/pages/index/index?inChannel=commonShare`,
                        imageUrl: "https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_lamer_cream_show/share/wx-share.jpg",
                }
        }
})